<template>
  <div class="Roles">
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <!-- 添加角色 -->
        <el-col>
          <el-button
            type="primary"
            v-btnpermission="'btn-roleadd'"
            @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="rolesList" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-row
                  :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']"
                  v-for="(item1, i1) in scope.row.children"
                  :key="item1.id"
                >
                  <!-- 渲染一级权限 -->
                  <el-col :span="5">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 渲染二和三级权限 -->
                  <el-col :span="19">
                    <!-- 通过 for 嵌套 渲染二级权限 -->
                    <el-row
                      v-for="(item2, i2) in item1.children"
                      :key="item2.id"
                      :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                    >
                      <el-col :span="6">
                        <el-tag
                          type="success"
                          closable
                          @close="removeRightById(scope.row, item2.id)"
                        >
                          {{ item2.authName }}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18">
                        <el-tag
                          type="warning"
                          :class="[i3 === 0 ? '' : 'bdtop']"
                          v-for="(item3, i3) in item2.children"
                          :key="item3.id"
                          closable
                          @close="removeRightById(scope.row, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <!-- <pre>
                  {{ scope.row }}
                </pre> -->
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="Name" label="角色名称"></el-table-column>
            <el-table-column prop="Desc" label="角色描述"></el-table-column>
            <el-table-column prop="Isvalid" label="是否有效">
              <template #default="scope">
                <el-switch v-model="scope.row.Isvalid" disabled />
              </template>
            </el-table-column>
            <el-table-column prop="IsExhibition" label="是否用于注册">
              <template #default="scope">
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  v-model="scope.row.IsExhibition"
                  disabled
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-roleupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-roledelete'"
                  @click="rolesdelete(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
                <el-button
                  size="small"
                  v-btnpermission="'btn-rolesend'"
                  @click="showSetRightDialog(scope.row)"
                  type="warning"
                  :icon="ElementPlus"
                  >分配权限</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      v-model="addDialogVisible"
      @close="addDislogClosed"
      width="30%"
    >
      <el-form
        :model="addRolesForm"
        :rules="rolesFormRulesMixin.addFormRules"
        ref="addDialogRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="Name">
          <el-input v-model="addRolesForm.Name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="Desc">
          <el-input v-model="addRolesForm.Desc"></el-input>
        </el-form-item>
        <el-form-item label="是否有效" prop="Isvalid">
          <el-checkbox v-model="addRolesForm.Isvalid" />
        </el-form-item>
        <el-form-item label="是否用于注册" prop="IsExhibition">
          <el-switch
            v-model="addRolesForm.IsExhibition"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRolesUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="修改角色"
      v-model="editDialogVisible"
      @close="editDislogClosed"
      width="30%"
    >
      <el-form
        :model="editDialogForm"
        :rules="rolesFormRulesMixin.editFormRules"
        ref="editDialogRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="Name">
          <el-input v-model="editDialogForm.Name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="Desc">
          <el-input v-model="editDialogForm.Desc"></el-input>
        </el-form-item>
        <el-form-item label="是否有效" prop="Isvalid">
          <el-checkbox v-model="editDialogForm.Isvalid"></el-checkbox>
        </el-form-item>
        <el-form-item label="是否用于注册" prop="IsExhibition">
          <el-switch
            v-model="editDialogForm.IsExhibition"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialogSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      v-model="SetRightDialogVisible"
      width="50%"
      @close="SetRightDialogVisibleClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expanded-keys="[1]"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <div style="margin-top: 20px">
        <el-text class="mx-1" type="primary">搜索范围</el-text>
        <el-radio-group
          v-model="radioSearch"
          v-for="(v, k) in searchOptions"
          :key="v.value"
          size="small"
        >
          <el-radio :label="v.value" border>{{ v.label }}</el-radio>
        </el-radio-group>
      </div>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="SetRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue';
import { useStore } from 'vuex';
import {
  netRoles,
  netAddRoles,
  netEditRolesById,
  netDeleteRolesById,
  netGiveRightForRole,
} from '@/network/roles.js';
import { getDicByDictionary } from '@/network/dictionary.js';
import { netRights } from '@/network/rights.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, ElementPlus } from '@element-plus/icons-vue';
import { rolesFormRulesMixin } from '@/utils/mixin.js';
// const { proxy } = getCurrentInstance();
const store = useStore();
// 所有角色的列表
let rolesList = ref([]);
// 所有权限的数据
let rightsList = ref([]);
// 添加角色对话框的显示和隐藏
let addDialogVisible = ref(false);
// 编辑对话框的显示和隐藏
let editDialogVisible = ref(false);
const radioSearch = ref();
let searchOptions = ref([]);
// 分配权限对话框的显示和隐藏
let SetRightDialogVisible = ref(false);
let addRolesForm = ref({
  Desc: '',
  Name: '',
  Isvalid: true,
  Permission: '',
  IsExhibition: 0,
});
let addDialogRef = ref(null);
const editDialogRef = ref(null);
const treeRef = ref(null);
const editDialogForm = ref({
  Code: 0,
  Desc: '',
  Name: '',
  Isvalid: true,
  Permission: '',
  IsExhibition: 0,
});
// 树形控件的绑定对象
const treeProps = ref({
  children: 'children',
  label: 'authName',
});
// 树形控件 -> 默认选中的节点id值数组
let defKeys = ref([]);
// 当前即将分配权限的角色的ID
let rolesId = ref('');
onBeforeMount(() => {
  getRolesList();
});

// 获取角色列表

const getRolesList = async () => {
  await netRoles().then((result) => {
    rolesList.value = result;
  });
  await getDicByDictionary({ type: 'searchBound' }).then((result) => {
    searchOptions.value = result;
  });
};
// 添加角色
const addRolesUser = async () => {
  addDialogRef.value.validate(async (valid) => {
    if (!valid) return;
    await netAddRoles(addRolesForm.value)
      .then(() => {
        ElMessage({
          type: 'success',
          message: '增加角色成功！',
        });
        getRolesList();
        addDialogVisible.value = false;
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error('新增失败！');
      });
  });
};
// 清空添加角色对话框
const addDislogClosed = async () => {
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};
const editDislogClosed = async () => {
  editDialogRef.value.resetFields();
  editDialogRef.value.clearValidate();
};
// 删除角色
const rolesdelete = async (id) => {
  await ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '删除角色', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await netDeleteRolesById({ code: id }).then(() => {
        ElMessage({
          type: 'success',
          message: '该用户已经删除',
        });
        getRolesList();
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error('修改失败！');
    });
};
// 得到修改用户的信息
const showEditDialog = async (row) => {
  editDialogForm.value = JSON.parse(JSON.stringify(row));
  editDialogVisible.value = true;
};
const editDialogSubmit = () => {
  editDialogRef.value.validate((valid) => {
    if (!valid) return;
    netEditRolesById(editDialogForm.value).then(() => {
      ElMessage({
        type: 'success',
        message: '修改角色成功!',
      }).catch((err) => {
        console.log(err);
        ElMessage.error('修改失败！');
      });
      getRolesList();
    });
    editDialogVisible.value = false;
  });
};
// 根据ID删除对应的权限
const removeRightById = async (roles, id) => {
  // 弹框提示用户是否删除
  await ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await netRoles(`roles/${roles.id}/rights/${id}`).then((res) => {
        // this.getRolesList()
        // 直接调用获取用户的方法会导致展开栏的关闭,这样体验不好
        // 可以直接把返回的最新数据直接赋值
        roles.children = res;
        console.log('删除');
      });
    })
    .catch(() => () => {
      ElMessage({
        type: 'error',
        message: '删除权限失败',
      });
    });
};
// 展示分配权限的对话框
const showSetRightDialog = async (row) => {
  let roles = { ...row };
  rolesId.value = roles.Code;
  // 获取所有权限列表
  await netRights().then((res) => {
    // 获取到的权限数据保存
    rightsList.value = res;
    //搜索权限赋值
    radioSearch.value = null;
    let sindex = roles.Permission && roles.Permission.indexOf('Search');
    if (sindex != null && sindex > -1) {
      radioSearch.value = roles.Permission.substring(sindex);
    }
    // 递归获取三级节点
    getLeafKeys(row, defKeys.value);
    // if (roles.Permission != null) {
    //   defKeys.value = roles.Permission.split(",");
    // }
    SetRightDialogVisible.value = true;
  });
};
// 递归的形式,获取角色下所有的三级权限的id,并保存到 defKeys数组中
const getLeafKeys = (node, arr) => {
  // 如果当前node没有children属性则是三级节点
  // console.log(node, arr, 'node');

  if (!node.children) {
    return arr.push(node.id);
  }
  node.children.forEach((item) => getLeafKeys(item, arr));
};
// 监听分配权限对话框的关闭事件
const SetRightDialogVisibleClosed = () => {
  // 清空 defkeys 数组  避免累积
  defKeys.value = [];
};
// 点击为角色分配权限
const allotRights = async () => {
  const keys = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ];
  if (radioSearch.value) {
    keys.push(radioSearch.value);
  }
  console.info(keys);
  const idStr = keys.join(',');
  await netGiveRightForRole({
    role: rolesId.value,
    rids: idStr,
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '分配权限成功!',
    });

    getRolesList();
    SetRightDialogVisible.value = false;
  });
  //保存角色权限
  store.dispatch('app/setRolePers', store.state.app.role);
  // location.reload();
};
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
